/**
 <p>form控件，一般用于弹出的主从表编辑窗口，底部默认包含保存和关闭按钮</p>
 * xtype = cceafbindingformpanel2

 * @module Ext-ux-cceaf-control
 * @class cceaf.control.BindingFormPanel2
 * @extends Ext.form.Panel
 * @since 1.0
 */
Ext.define('cceaf.control.BindingFormPanel2',{
	extend: 'Ext.form.Panel', 
    alias: 'widget.cceafbindingformpanel2',
    requires: [
        'cceaf.ControlDefaultConfig',
        'cceaf.control.Button',
        'cceaf.control.FieldSet'
    ],

    /**
	 * 是否有关闭按钮
	 *
     * @property hasClose 
     * @type Boolean
     * @default true
     */
    hasClose: true,
    
    /**
	 * 是否有返回按钮
	 *
     * @property hasBack 
     * @type Boolean
     * @default true
     */
    hasBack: false,
    
	constructor: function(config){
		config = config || {};
        
		cceaf.control.BindingFormPanel2.superclass.constructor.apply(this, arguments);
	},
	
	initComponent : function(){
		var config = this;
		
		var layout = config.layout;
		var columns = config.columns;
        if(columns != null){
        	layout = {
	        	type: 'table',
	        	columns: columns
	        };
        	config = Ext.apply(config, {layout: layout});
        }
        
        var operateArea = [],i=0;
		if (config.operateArea) {
			operateArea = config.operateArea;
		} else { //默认操作区
			{
				operateArea[i] = {itemId: 'btnSave', text: '保存', xtype: 'cceafbutton', iconCls: 'saveIcon'};
				i++;
				operateArea[i] = '-';
				i++;
				
				if (config.hasClose) {
					operateArea[i] = {itemId: 'btnClose', text: '关闭',xtype: 'cceafbutton', iconCls: 'closeIcon'};
					i++;
				}
				
				if (config.hasBack) {
					operateArea[i] = {itemId: 'btnBack', text: '返回',xtype: 'cceafbutton', iconCls: 'backIcon'};
					i++;
				}
			}
		}
		
		var defaultFormButtonsAreaHeight = szpshang.Global.DEFAULT_FORM_BUTTONS_AREA_HEIGHT;
		config = Ext.applyIf(config, {
			bodyStyle: 'padding:10px 10px',
	        //anchor: '100% 100%',
	        waitMsgTarget: true,
	        defaults:{  
    			//bodyStyle:'padding:0px 5px 0px 0px',
    			layout: {
			        type: 'hbox',
			        align: 'middle'
			    },
    			baseCls:'x-plain',
    			padding: '5 5 5 5',
    			xtype:'cceaffieldset'
            },
	        //buttons: operateArea
	        dockedItems: [{
	            xtype: 'toolbar',
	            dock: 'bottom',
	            layout: { pack: 'end'},
	            height: defaultFormButtonsAreaHeight,
	            ui: 'footer',
	            items: operateArea
	        }]
		});
		
		cceaf.control.BindingFormPanel2.superclass.initComponent.call(this);
	},
	
	initEvents: function() {
    	cceaf.control.BindingFormPanel2.superclass.initEvents.call(this);
    	
    	//注册保存按钮事件
    	var btnSave = this.down('#btnSave');
    	if (btnSave) {
			btnSave.on('click',this.page_save);
		}
    	
    	//注册关闭按钮事件
		var btnClose = this.down('#btnClose');
		if (btnClose) {
			btnClose.on('click',this.page_close);
		}
    	
		//注册返回按钮事件
		var btnBack = this.down('#btnBack');
		if (btnBack) {
			btnBack.on('click',this.page_back);
		}
		
    	//注册其他事件
    	this.registerEvent();
    },
    
    
    /**
	 * form的父容器，grid或tree
	 *
     * @property fatherPanel 
     * @type Panel
     * @default null
     */
    fatherPanel: null,
	
	/**
	 * 新增、编辑和删除等操作后，需要更新的组件itemId集合（该组件带有store属性）
	 *
     * @property updatePanelItemIds 
     * @type String 用“,”分割
     * @default null
     */
	updatePanelItemIds: null,
	
	/**
	 * 提交后是否重新载入父对象的stroe
	 *
     * @property storeLoad 
     * @type Boolean
     * @default true
     */
	storeLoad: true,
	
	/**
	 * 保存时校验从表是否一定要有数据
	 *
     * @property detailValid 
     * @type Boolean
     * @default true
     */
	detailValid: true,
	
	/**
	 * 是否form提交
	 *
     * @property formSubmit 
     * @type Boolean
     * @default true
     */
	formSubmit: true,
	
	/**
	 * 提交成功后是否重新加载form数据
	 *
     * @property formLoad 
     * @type Boolean
     * @default false
     */
	formLoad: false,
	
    /**
    * 保存对象
    */
    page_save: function(){
    	var billForm = this.up('cceafbindingformpanel2');
    	var formLoad = billForm.formLoad;
    	var storeLoad = billForm.storeLoad;
    	var detailValid = billForm.detailValid;
    	var formSubmit = billForm.formSubmit;
    	
    	var submitParam = {
    		formSubmit: formSubmit, //false为ajax提交
			detailValid: detailValid, //true表示detail不能为空
			closePopWin: true,  //保存数据后关闭窗口
			storeLoad: storeLoad,//提交数据后重新载入数据
			formLoad: formLoad //提交成功后是否重新加载form数据
    	};
		
		billForm.page_submit(submitParam);
    },
    
    
    /**
    * 页面数据提交
    * <br> submitParam = {
    * <br> 	 formSubmit: false, //false为ajax提交，true为form.submit
    * <br>   detailValid: true, //true表示detail不能为空
    * <br>   actionURL： '',	//提交的action
    * <br>   closePopWin: true, //保存数据后关闭窗口
    * <br>   formLoad: false, //提交数据后重新载入数据
    * <br>   storeLoad: false //提交后是否加载列表页面的store
    * <br> }
    *
    * @param {attribute} submitParam 提交参数
    * @param {Function} callback 回调函数
    */
    page_submit: function(submitParam, callback){
    	var billForm = this;
    	var fatherPanel = billForm.fatherPanel;
    	
    	if(fatherPanel == null){
    		cceaf.util.ExtHelper.showErrorDialog('请设置form的fatherPanel！');
    		return;
    	}
    	
    	var formSubmit = false;
    	var detailValid = true;
    	var closePopWin = true;
    	var formLoad = false;
    	var storeLoad = true;
    	var actionURL;
    	
    	if(fatherPanel.pageStatus == 'add'){
    		actionURL = fatherPanel.addAction;
    	}
    	else{
    		actionURL = fatherPanel.editAction;
    	}
    	
    	if (submitParam) {
    		if ( Ext.isDefined( submitParam.formSubmit )) {
    			formSubmit = submitParam.formSubmit;
    		}
    		if ( Ext.isDefined( submitParam.detailValid )) {
    			detailValid = submitParam.detailValid;
    		}
    		if ( Ext.isDefined( submitParam.actionURL )) {
    			actionURL = submitParam.actionURL;
    		}
    		if ( Ext.isDefined( submitParam.closePopWin )) {
    			closePopWin = submitParam.closePopWin;
    		}
    		if ( Ext.isDefined( submitParam.formLoad )) {
    			formLoad = submitParam.formLoad;
    		}
    		if ( Ext.isDefined( submitParam.storeLoad )) {
    			storeLoad = submitParam.storeLoad;
    		}
    	}
    
    	if (!actionURL) {
     		cceaf.util.ExtHelper.showInfoDialog("action 没有定义！");
     		return; 
     	}
 		
     	if(!billForm.form.isValid()){
 			return;
 		}
     	if(!billForm.checkForm()){
     		return;
     	}
     	
     	//校验明细数据
     	var detailGrid = billForm.down('#' + billForm.detailItemId);
     	if (!detailGrid) {
     		detailGrid = billForm.down('gridpanel');
     	}
     	var billStore = detailGrid.getStore();
     	
		var gridRowNumber = billStore.data.length;
		if(gridRowNumber == 0 && detailValid){
			cceaf.util.ExtHelper.showInfoDialog('请输入明细数据');
			return false;
		}
		if(detailValid){
			//校验细表已经输入 的数据字段
			var gridColumnNumber = detailGrid.columns.length;
			var detailModel = detailGrid.model;
			for(var i=0;i<gridRowNumber;i++){
				var gridRow = billStore.getAt(i).data;
				
				for(var j=1;j<gridColumnNumber;j++){
					var column = detailGrid.columns[j];
					if(column.getEditor(detailModel) && column.getEditor(detailModel).allowBlank == false){
						var dataIndex = column.dataIndex;
						var cellValue = eval('gridRow.' + dataIndex);
	
						if(!Ext.isDefined(cellValue) || Ext.isEmpty(cellValue)){
							detailGrid.getPlugin('pluginIdOfcceafdetaileditorgridpanel').startEditByPosition({row:i, column:j});
	        				return;
	        			}
					}
				}
			}
		}
		//组装细表JSONString
		var detailJSONData = [];
		for(var i=0;i<gridRowNumber;i++){
			//var gridRow = billStore.getAt(i).data;
			detailJSONData.push(billStore.getAt(i).data);
		}
		var detailJSONString = Ext.JSON.encode(detailJSONData);
      	//提交数据到服务器
      	if (formSubmit) {
      		billForm.form.submit({
	        	url:  actionURL,
	        	params: {
	      			detailJSONString: detailJSONString
	      		},
	        	waitMsg : '正在保存数据...',
	            success: function(from, action) { 
	            	cceaf.util.ExtHelper.showInfoDialog(action.result.message); 
	            	
	            	if ( formLoad ) {
	            		billForm.page_load(action);
	            	}
	            	
	            	var addAndEditWin = billForm.findParentByType('window');
	    			if (addAndEditWin) {
	    				if (closePopWin) {
	    					addAndEditWin.hide();
	    				}
	    				
	    				//数据提交后，需要更新查询数据
	    				if (storeLoad) {
	    					//fatherPanel.getStore().load({params:{isquery:true}});
	    					//以上方法不会带入查询条件，以下直接触发查询按钮的click事件
	    					var btnQuery = fatherPanel.down('#btnQuery');
		    				if(btnQuery) {
		    					btnQuery.fireEvent('click');
		    				} else {
		    					fatherPanel.getStore().load({params:{isquery:true}});
		    				}
		    				
	    					var updatePanelItemIds = billForm.updatePanelItemIds;
	    					if (updatePanelItemIds != null) {
	    						Ext.Array.each(updatePanelItemIds.split(","), function(updatePanelItemId){
	    							//假定updatePanel与fatherPanel在同一级
		    						var updatePanel = fatherPanel.up().down('#' + updatePanelItemId);
		    						if (updatePanel != null && updatePanel.getStore()) {
		    							updatePanel.getStore().load({params:{isquery:true}});
		    						}
		    					});
	    					}
	    				}
	    			} 
	    			
	    			if ( Ext.isDefined(callback) ) {
	    				callback();
	    			}
	            },
	            failure: function(from, action) {
	            	if(action.result == null) return;
	            	/*
	            	var addAndEditWin = billForm.findParentByType('window');
	    			if (addAndEditWin) {
	    				if (closePopWin) {
	    					addAndEditWin.hide();
	    				}
	    			}*/
	    			
	            	cceaf.util.ExtHelper.showErrorDialog(action.result.message);   
	            }
	        });	
      	} else {
      		//组装主表 JSONString
    		var masterJSONData = new Object();
    		var formFields = billForm.query('.field');
    		for(var i=0; formFields != null && i<formFields.length; i++){
         		var item = formFields[i];
         		var itemId = item.getName(); //注意:此处最好用getName,而不用getId
     			var itemValue = item.getValue();
     			
     			if(Ext.isDate(itemValue)){
     				itemValue = Ext.Date.format(itemValue,'Y-m-d');
     			}
     			
     			if (item.getXType() != 'filefield') {
     				var splitIndex = itemId.indexOf("-");
     				if( splitIndex > 0) {
     					cceaf.util.ExtHelper.showInfoDialog('必须设置' + itemId.substr(itemId, splitIndex) + '字段的name属性！');
     					return;
     				}
     				if(item.getXType()=='radiofield'){
	 					if(item.checked){
	 						itemValue = item.inputValue;
	 						eval("masterJSONData." + itemId + " = '" + itemValue + "'");
	 					}
     				}else{
     					eval("masterJSONData." + itemId + " = '" + itemValue + "'");
     				}
     			}
         	}
    		
        	var masterJSONString = Ext.JSON.encode(masterJSONData);
	      	Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
	      	Ext.Ajax.request({
	      		url:  actionURL,
	      		params: {
	      			masterJSONString: masterJSONString,
	      			detailJSONString: detailJSONString
	      		},
	      		success: function(response){
	      			var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
	   				
	    			var addAndEditWin = billForm.findParentByType('window');
	    			if (addAndEditWin && isProcessSucess) {
	    				//数据提交后，需要更新查询数据
	    				if (closePopWin) {
	    					addAndEditWin.hide();
	    				}
	    				
	    				//数据提交后，需要更新查询数据
	    				if (storeLoad) {
	    					//fatherPanel.getStore().load({params:{isquery:true}});
	    					//以上方法不会带入查询条件，以下直接触发查询按钮的click事件
	    					var btnQuery = fatherPanel.down('#btnQuery');
		    				if(btnQuery) {
		    					btnQuery.fireEvent('click');
		    				} else {
		    					fatherPanel.getStore().load({params:{isquery:true}});
		    				}
	    				}
	    			}  
	    			
	    			if (callback) {
	    				callback();
	    			}
	   			},
	   			failure: function(response){
	   				cceaf.util.ExtHelper.processAjaxRequest(response,false);
	   			}
	      	});
      	}
    },
    
    /**
    * 页面提交成功后重新载入
    * 
    * @param {Ext.form.action.Action} action form载入后返回的action数据
    */
    page_load: function(action){
    	billForm = this;
    	var fatherPanel = billForm.fatherPanel;
		if(fatherPanel == null){
    		cceaf.util.ExtHelper.showErrorDialog('请设置form的fatherPanel！');
    		return;
    	}
    	
    	var masterkeys = fatherPanel.masterKeyIds.split(',');
    	var url = fatherPanel.findByKeyAction + '?';
    	
    	for(var i=0;i<masterkeys.length;i++){
			var temp = eval("action.result." + masterkeys[i]);
			url += masterkeys[i] + '=' + temp + '&';
		}
		billForm.form.reset();
		
		var detailGrid = billForm.down('#' + billForm.detailItemId);
     	if (!detailGrid) {
     		detailGrid = billForm.down('gridpanel');
     	}
     	var billStore = detailGrid.getStore();
     	billStore.removeAll();
     	
    	//装载对象到表单
    	billForm.form.load({
	        //waitMsg : '正在载入数据...',
	        url:  url,
    		success: function(form,action) { 
	        	//表单载入数据时,设置特殊值,包括载入细表数据
    			billForm.initEditPage(action);
    			
	        	//显示正确提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
	        },
	        failure: function(form,action) {
	        	//显示错误提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
	        }
	   	});
    },
    
    /**
    * 根据页面上对象主键加载页面数据
    *
    */
    form_load: function(){
    	billForm = this;
    	var fatherPanel = billForm.fatherPanel;
		if(fatherPanel == null){
    		cceaf.util.ExtHelper.showErrorDialog('请设置form的fatherPanel！');
    		return;
    	}
		
    	var masterkeys = fatherPanel.masterKeyIds.split(',');
    	var url = fatherPanel.findByKeyAction + '?';
    	for(var i=0;i<masterkeys.length;i++){
    		var keyValue = Ext.getCmp(masterkeys[i]).getValue();
			url += masterkeys[i] + '=' + keyValue + '&';
		}
		
		billForm.form.reset();
		
		var detailGrid = billForm.down('#' + billForm.detailItemId);
     	if (!detailGrid) {
     		detailGrid = billForm.down('gridpanel');
     	}
     	var billStore = detailGrid.getStore();
     	billStore.removeAll();
		
    	//装载对象到表单
    	billForm.form.load({
	        //waitMsg : '正在载入数据...',
	        url: url,
    		success: function(form,action) { 
	        	//表单载入数据时,设置特殊值,包括载入细表数据
    			billForm.initEditPage(action);
    			
	        	//显示正确提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
	        },
	        failure: function(form,action) {
	        	//显示错误提示
	        	var jsonObject =eval("(" + action.response.responseText + ")");
	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
	        }
	   	});
    },
    
    /**
     * 表单提交后需要重新载入数据后设置form的特殊值
     */
    initEditPage: function(action){
    	
    },
    
    /**
    * 关闭页面
    *
    */
    page_close: function(){
    	var billForm = this.findParentByType('cceafbindingformpanel2');
    	var addAndEditWin = billForm.findParentByType('window');
    	if (addAndEditWin) {
    		addAndEditWin.hide();
    	}
    },
    
    /**
     * 返回到查询列表
     *
     */
     page_back: function(){
     	var billForm = this.up('cceafbindingformpanel2');
     	var cardPanel = billForm.up('panel');
     	
     	cardPanel.getLayout().setActiveItem(0);
     },
     
    /**
    * form的特殊检验（是否为空的校验根据field的allowBlank属性），默认不校验
    *
    * @return {Boolean} 校验成功范围true
    */
    checkForm: function(){
    	return true;
    },
    
    /**
     * 注册其他事件
     */
    registerEvent: function(){
    	
    },
    
    /**
     * 设置form中field的readonly属性
     * @param {boolean} readOnly 是否只读
     */
    setReadOnly: function(readOnly){
    	var billForm = this;

    	var fields = billForm.query('textfield');
    	Ext.Array.each(fields, function(field){
    		field.setReadOnly(readOnly);
    	});
    }
    
});